<template>
    <div>
        <div style="width: 100%; margin-left: 20px; margin-top: 50px;">
            <el-col v-for="item in chartList" :key="item.id" style="margin: 5px" :span="10">
                <el-card v-loading="loading">
                    <el-descriptions title="分析表格">
                        <el-descriptions-item label="图表名">{{ item.name }}</el-descriptions-item>
                        <el-descriptions-item :span="2" label="分析目标">{{ item.goal }}</el-descriptions-item>
                        <el-descriptions-item :span="2" label="分析时间">{{ item.createTime }}</el-descriptions-item>
                        <el-descriptions-item label="图表类型">
                            <el-tag size="small">{{ item.chartType }}</el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item :span="3" label="图表结论">{{ item.genResult }}</el-descriptions-item>
                        <el-descriptions-item :span="3" label="图表">
                            <div v-if="item.status === 2" :id="'genChart' + item.id" style="height: 400px; width: 80%;"></div>
                            <div v-else style="height: 400px; width: 80%;">
                                <el-result v-if="item.status === 0" icon="warning" title="警告提示" subTitle="当前任务执行繁忙，请耐心等待"></el-result>
                                <el-result v-else-if="item.status === 1" icon="info" title="信息提示" subTitle="任务正在执行，请稍后查看"></el-result>
                                <el-result v-else-if="item.status === 3" icon="error" title="错误提示" subTitle="任务执行失败，请重试" >
                                    <template slot="extra">
                                        <span>{{ item.message }}</span> <br/><br/>
                                        <el-button type="danger" size="mini" @click="openDialog(item.id)">重新生成</el-button>
                                    </template>
                                </el-result>
                            </div>
                        </el-descriptions-item>
                    </el-descriptions>
                </el-card>
            </el-col>
            <el-pagination
            v-loading="loading"
            style="position: absolute;top: 75px;left: 50%;transform: translateX(-50%);"
            background
            layout="prev, pager, next"
            :pageSize.sync="pageSize"
            :current-page.sync="pageNo"
            @current-change="changeChart"
            :total="totalCount"
            >
            </el-pagination>
        </div>
        <el-dialog
            title="重新上传"
            :visible.sync="dialogVisible"
            width="30%"
            >
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="分析目标" prop="goal">
                <el-input type="textarea" placeholder="请输入分析目标" :maxLength="100" v-model="form.goal"></el-input>
                </el-form-item>
                <el-form-item label="图表名称" prop="name">
                <el-input placeholder="请输入图表名称" v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="图表类型" prop="chartType">
                <el-select placeholder="请选择图表类型" v-model="form.chartType">
                    <el-option label="柱状图" value="柱状图"></el-option>
                    <el-option label="折线图" value="折线图"></el-option>
                    <el-option label="饼图" value="饼图"></el-option>
                    <el-option label="雷达图" value="雷达图"></el-option>
                </el-select>
                </el-form-item>
                <el-form-item label="原始数据">
                <el-upload
                action="/upload"
                    :before-upload="beforeFileUpload"
                    :limit="1"
                    :http-request="handleUpload"
                    :on-exceed="handleExceed"
                    :file-list="fileList">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件，且不超过1MB</div>
                </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelDialog">取 消</el-button>
                <el-button type="primary" @click="onSubmit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import * as echarts from "echarts";
export default {
    data() {
        return {
            user: JSON.parse(localStorage.getItem('xm-user')) || {},
            chartList: [],
            pageSize: 2,
            pageNo: 1,
            totalCount: 1,
            loading: false,
            dialogVisible: false,
            form: {
                goal: '',
                name: '',
                chartType: ''
            },
            rules: {
                goal: [
                { required: true, message: '请输入分析目标', trigger: 'blur' },
                ],
                name: [
                { required: true, message: '请输入图表名称', trigger: 'blur' },
                ],
                chartType: [
                { required: true, message: '请选择图表类型', trigger: 'blur' },
                ]
            },
            fileList: [],
            fileObj: null,
        }
    },
    created() {
        this.getChartList()
    },
    methods: {
        cancelDialog() {
            this.dialogVisible = false
            this.form = {},
            this.fileList = [],
            this.fileObj = null
        },
        async openDialog(chartId) {
            if (!chartId) {
                this.$message.error('请选择图表')
                return
            }
            this.dialogVisible = true
            let res = await this.$request.post(`/chart/getChartById/${chartId}`)
            if (res.code === 200) {
                this.$nextTick(() => {
                    this.form.goal = res.data.goal
                    this.form.name = res.data.name
                    this.form.chartType = res.data.chartType
                    this.form.id = chartId
                })
            }
        },
        changeChart(currentPage) {
            this.pageNo = currentPage
            this.getChartList()
        },
        async getChartList() {
            this.loading = true
            await this.$request.post('/chart/loadDataList', {
                pageNo: this.pageNo,
                pageSize: this.pageSize,
                userId: this.user.id
            }).then((res) => {
                if (res.code === 200) {
                    this.chartList = res.data.list
                    this.totalCount = res.data.totalCount
                    this.$nextTick(() => {
                        this.handleChartGen()
                    })
                }
            }).finally(() => {
                this.loading = false
            })
        },
        handleChartGen() {
            this.chartList.forEach((item) => {
               if (item.status === 2) {
                    this.genChart(item.genChart, 'genChart' + item.id)
                }
            })
        },
        genChart(option, id) {
            let myChart = echarts.init(document.getElementById(id));
            var jsonStr = option.replace(/'/g, '"').replace(';', '');
            jsonStr = jsonStr.replace(/^option=/, '');
            var optionObj;
            try {
                optionObj = eval("("+jsonStr+")"); 
            } catch (e) {
            this.$message.error('图表数据有误，请检查');
            return false 
            }
            myChart.setOption(optionObj)
      },
      handleExceed(files, fileList) {
        this.$message.warning(`只能上传一个文件`);
      },
      beforeFileUpload(file) {
        const isLt1MB = file.size / 1024 / 1024 < 1;
        const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        if (file === null) {
          this.$message.error('请选择文件');
        }
        if (!isExcel) {
          this.$message.error('只能上传xls/xlsx文件');
          return false
        }
        if (!isLt1MB) {
          this.$message.error('文件大小不能超过1MB');
          return false
        }
        this.fileObj = file
      },
      async onSubmit() {
        await this.$refs.form.validate(valid => {
          if (valid) {
            if (this.fileObj === null) {
              this.$message.error('请上传文件')
              return
            }
            const formData = new FormData()
            formData.append('file', this.fileObj)
            formData.append('goal', this.form.goal)
            formData.append('name', this.form.name)
            formData.append('chartType', this.form.chartType)
            formData.append('id', this.form.id)

            this.loading = true

            this.$request.post('/chart/generate/async', formData, {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }).then((res) => {
              if (res.code === 200) {
                // this.formRes = res.data
                // this.genChart(res.data.jsCode)
                // this.$message.success('图表生成成功')
                this.$message.success('图表生成成功，稍后请到“我的图表”查看')
                this.form = {}
                this.dialogVisible = false
                this.fileList = []
                this.fileObj = null
                this.getChartList()
              } else {
                this.$message.error(res.message)
              }
            }).finally(() => {
              this.loading = false
            })
          }
        })
      },
      handleUpload() {
        // 提供这个，就不需要指定action
      },
    }
}
</script>

<style scoped>

</style>